<?php
/**
 * Created by PhpStorm.
 * User: work
 * Date: 18-6-24
 * Time: 下午1:47
 */

namespace PddWechat\Models\User\Service;


use Dai\Framework\Base\BaseException;
use Dai\Framework\Base\BaseService;
use Dai\Framework\Library\Log;
use Dai\Framework\Library\RedisExt;
use PddWechat\Library\WechatLibrary;
use PddWechat\Models\User\Data\UserData;
use PddWechat\Models\User\DataObject\UserDo;
use PddWechat\Models\User\Dto\WechatUserBasicInfo;
use PddWechat\Models\User\Param\TokenCreateParam;
use PddWechat\Models\User\Response\TokenCreateResponse;

class TokenCreate extends BaseService
{
    public function __construct()
    {
        $this->dataUser = new UserData();
    }

    /**
     * @param $basePageInfo
     * @return TokenCreateResponse
     * @throws BaseException
     */
    public function execute($basePageInfo)
    {
        /** @var TokenCreateParam $params */
        $params = $basePageInfo->params;
        //通过code换取openId和token
        $wechatUserInfo = WechatLibrary::getWechatOpenIdInfo($params->code);

        //查询数据库有没有这个openId
        $userDo = $this->dataUser->getUserByOpenId($wechatUserInfo->openid);
        if($userDo == null) {
            $basicUserInfo = WechatLibrary::getBasicUserInfo($wechatUserInfo->openid, $wechatUserInfo->access_token);
            $wechatUserBasicInfo = new WechatUserBasicInfo();
            $wechatUserBasicInfo->openId = $basicUserInfo->openId;
            $wechatUserBasicInfo->nickname = $basicUserInfo->nickname;
            $wechatUserBasicInfo->province = $basicUserInfo->province;
            $wechatUserBasicInfo->headimgurl = $basicUserInfo->headimgurl;
            $wechatUserBasicInfo->city = $basicUserInfo->city;
            $wechatUserBasicInfo->unionid = $basicUserInfo->unionid;
            $wechatUserBasicInfo->sex = $basicUserInfo->sex;
            $userDo = $this->dataUser->insert($wechatUserBasicInfo, 0);
        }
        //放入缓存
        RedisExt::getInstance()->set($wechatUserInfo->access_token, json_encode($userDo, JSON_UNESCAPED_UNICODE));
        $tokenCreateResponse = new TokenCreateResponse();
        $tokenCreateResponse->token = $wechatUserInfo->access_token;
        return $tokenCreateResponse;
    }
}
